import React, { Component } from 'react'
import classNames from 'classnames'
import history from 'router/history'
import { blowfish } from 'utils/tools'
import { verifyCode, userRegister } from 'utils/Api'
import { codeUrl } from '../../url'
import { toast } from 'react-toastify'

class RegisterForm extends Component {
  constructor() {
    super()
    this.state = {
      code: undefined,
      username: '',
      password: '',
      confirmPassword: '',
      protocol: false,
      codeNumber: '',
      timestamp: (new Date()).valueOf()
    }
  }
  getCode = (e) => {
    e.preventDefault()
    this.changeImg()
  }
   
  registerSubmit = (e) => {
    e.preventDefault()

    const {
      username,
      password,
      confirmPassword,
      protocol,
      codeNumber,
      timestamp,
    } = this.state

    if (!username) {
      toast.info('请输入用户名', {
        position: toast.POSITION.BOTTOM_CENTER,
        pauseOnHover: false,
        hideProgressBar: true,
        autoClose: 3000,
      })
      return
    }
    if (!username.match(/^[a-zA-Z\u4e00-\u9fa5][\s\S]*/)){
      toast.info('输入用户名格式不正确', {
        position: toast.POSITION.BOTTOM_CENTER,
        pauseOnHover: false,
        hideProgressBar: true,
        autoClose: 3000,
      })
      return
    } else {
      let len = username.replace(/[^x00-xff]/g, 'aa').length
      if (len > 24 || len < 6) {
        toast.info('输入用户名格式不正确', {
          position: toast.POSITION.BOTTOM_CENTER,
          pauseOnHover: false,
          hideProgressBar: true,
          autoClose: 3000,
        })
        return
      }
    }
    if(!password) {
      toast.info('输入密码', {
        position: toast.POSITION.BOTTOM_CENTER,
        pauseOnHover: false,
        hideProgressBar: true,
        autoClose: 3000,
      })
      return
    }
    if (!password.match(/^[^\u4e00-\u9fa5]{6,24}$/)) {
      toast.info('输入密码格式不正确', {
        position: toast.POSITION.BOTTOM_CENTER,
        pauseOnHover: false,
        hideProgressBar: true,
        autoClose: 3000,
      })
      return
    }
    if (!confirmPassword) {
      toast.info('请确认密码', {
        position: toast.POSITION.BOTTOM_CENTER,
        pauseOnHover: false,
        hideProgressBar: true,
        autoClose: 3000,
      })
      return
    }
    if (confirmPassword !== password) {
      toast.info('两次密码不一样', {
        position: toast.POSITION.BOTTOM_CENTER,
        pauseOnHover: false,
        hideProgressBar: true,
        autoClose: 3000,
      })
      this.setState({
        password: '',
        confirmPassword: ''
      })
      return
    }
    verifyCode({
      timestamp,
      verifyCode: codeNumber,
    })
      .then(({ msg }) => {
        if (msg === '200') {
          return true
        }
      })
      .then(flag => {
        flag &&
          userRegister({
            username,
            password: blowfish(password)
          })
            .then(({ msg, result }) => {
              if (msg === '200') {
                history.push('/validate')
                sessionStorage.setItem('token', result)
              }
            })   
      }) 
  }
  changeImg = () => {
    this.setState({
      timestamp: (new Date()).valueOf()
    })
  }
  inputChange = (e) => {
    const { name, value } = e.target
    if (name === 'protocol') {
      this.setState({
        protocol: !this.state.protocol
      })
      return
    }
    this.setState({
      [name]: value
    })
  }
  render() {
    return (
      <div className='register-from center'>
        <form onSubmit={this.registerSubmit}>
          <div className='from-items'>
            <label className='item-key'>用户名</label>
            <div className='from-item'>
              <input type="text"
                name='username'
                placeholder='用户名'
                required
                value={this.state.username}
                onChange={this.inputChange}/>
              <span className={classNames({
                'register-prompt': true,
              })}>由汉字、英文字母、数字或下划线组成，首字符不能为数字和特殊字符。6-24位，一个汉字占两个字符。</span>
            </div>
          </div>
          <div className='from-items'>
            <label className='item-key'>密码</label>
            <div className='from-item'>
              <input
                type="password"
                name='password'
                placeholder='********'
                required
                value={this.state.password}
                onChange={this.inputChange} />                                
              <span className={classNames({
                'register-prompt': true,
              })}>由英文字母、数字或英文特殊字符组成，6-24位。</span>
            </div>
          </div>
          <div className='from-items'>
            <label className='item-key'>确认密码</label>
            <div className='from-item'>
              <input
                type="password"
                name='confirmPassword'
                placeholder='********'
                required
                value={this.state.confirmPassword}
                onChange={this.inputChange} />
            </div>
          </div>
          <div className='verification-code '>
            <label className='item-key'>验证码</label>
            <div className='center'>
              <input
                type="text"
                required
                name='codeNumber'
                value={this.state.codeNumber}
                onChange={this.inputChange} />
              <img src={codeUrl+this.state.timestamp} alt="" />
              <a href="#" onClick={this.getCode}>看不清？换一张</a>
            </div>
          </div>
          <div className='from-items'>
            <label className='item-key'></label>
            <div className='from-checkbox center'>
              <input
                type="checkbox"
                className='register'
                name="protocol"
                id='protocol'
                required
                checked={this.state.protocol}
                onChange={this.inputChange}/>                                
              <label htmlFor='protocol' >
                同意 《<a href="./terms.htm" target='_blank'>精禾云平台服务条款</a>》
              </label>
            </div>
          </div>
          <div className='from-items'>
            <label className='item-key'></label>
            <input type="submit" className='register-submit' value='下一步' />
          </div>
        </form>
      </div>
    )
  }
}
export default RegisterForm